package xmu.crms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import xmu.crms.dto.ClassDTO;
import xmu.crms.entity.ClassInfo;
import xmu.crms.entity.Location;
import xmu.crms.entity.Seminar;
import xmu.crms.exception.*;
import xmu.crms.mapper.ClassMapper;
import xmu.crms.service.ClassService;
import xmu.crms.service.SeminarGroupService;
import xmu.crms.service.SeminarService;
import xmu.crms.service.TimerService;
import xmu.crms.service.impl.TimerServiceImpl;
import xmu.crms.util.JwtUtil;
import xmu.crms.vo.ClassProportionsVO;
import xmu.crms.vo.ClassVO;
import xmu.crms.vo.GroupVO;
import xmu.crms.vo.StudentVO;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *
 * @author status200
 * @date 2017/11/29
 */
@RestController
public class ClassController {
    @Autowired
    private ClassService classService;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private SeminarService seminarService;
    @Autowired
    private SeminarGroupService seminarGroupService;
    @Autowired
    private TimerService timerService;

    @GetMapping("/class")
    public ResponseEntity<List<ClassVO>> getClasses(@RequestHeader("Authorization") String authString) throws ClassesNotFoundException {
        //get userId
        BigInteger userId = JwtUtil.getIdFromAuthString(authString);

        List<ClassVO> vos = new ArrayList<>();
        List<ClassInfo> classInfos=classService.listClassByUserId(userId);
        for(ClassInfo x:classInfos){
            ClassVO vo=new ClassVO();
            vo.setId(x.getId());
            vo.setName(x.getName());
            List<Integer> numStudent=classMapper.getStudentNumByClassId(x.getId());
            vo.setNumStudent(numStudent.size());
            vo.setTime(x.getClassTime());
            vo.setSite(x.getSite());
            vo.setCourseName(x.getCourse().getName());
            vo.setCourseTeacher(x.getCourse().getTeacher().getName());
            //加上courseId
            vo.setCourseId(classService.getClassByClassId(x.getId()).getCourse().getId());
            vos.add(vo);
        }
        return new ResponseEntity<List<ClassVO>>(vos, HttpStatus.OK);
    }


    @GetMapping("/class/{classId}")
    public ResponseEntity<ClassVO> getClass(@PathVariable("classId") BigInteger classId) throws ClassesNotFoundException, SeminarNotFoundException {

        ClassInfo classInfo=classService.getClassByClassId(classId);
        List<Integer> numStudent=classMapper.getStudentNumByClassId(classId);
        ClassVO vo = new ClassVO();
        vo.setId(classInfo.getId());
        vo.setName(classInfo.getName());
        vo.setTime(classInfo.getClassTime());
        vo.setSite(classInfo.getSite());
        vo.setNumStudent(numStudent.size());
        //加上courseId
        vo.setCourseId(classService.getClassByClassId(classInfo.getId()).getCourse().getId());
        List<BigInteger> seminarId= classMapper.listSeminarIdByClassId(classInfo.getId());
        BigInteger currentSeminarId=new BigInteger(String.valueOf(-1));
        for(BigInteger x:seminarId){
            Seminar seminar=seminarService.getSeminarBySeminarId(x);
            Date startTime=seminar.getStartTime();
            Date endTime=seminar.getEndTime();
            Date currentDate=new Date();
            if(startTime.getTime()>=currentDate.getTime()&&currentDate.getTime()>=endTime.getTime()){
                currentSeminarId=seminar.getId();
            }
        }
        if(!currentSeminarId.equals(new BigInteger(String.valueOf(-1)))){
            Location location=classService.getCallStatusById(classInfo.getId(),currentSeminarId);
            if(location.getStatus()==1){
                vo.setCalling(currentSeminarId.intValue());
            }
            else{
                vo.setCalling(-1);
            }
        }
        else{
            vo.setCalling(-1);
        }
        //无roster属性 todo：
        vo.setRoster("/roster/Roster.xlsx");
        ClassProportionsVO classProportionsVO = new ClassProportionsVO();
        classProportionsVO.setA(classInfo.getFivePointPercentage());
        classProportionsVO.setB(classInfo.getFourPointPercentage());
        classProportionsVO.setC(classInfo.getThreePointPercentage());
        classProportionsVO.setReport(classInfo.getReportPercentage());
        classProportionsVO.setPresentation(classInfo.getPresentationPercentage());
        vo.setProportions(classProportionsVO);

        return new ResponseEntity<>(vo, HttpStatus.OK);
    }

    @PutMapping("/class/{classId}")
    public ResponseEntity updateClass(@PathVariable("classId") BigInteger classId,@RequestBody ClassDTO dto) throws ClassesNotFoundException, SeminarNotFoundException, GroupNotFoundException, UserNotFoundException, InvalidOperationException {
        ClassInfo classInfo=classService.getClassByClassId(classId);
        BigInteger currentSeminarId=new BigInteger(""+dto.getCalling());
        //若是开始签到
        if(!currentSeminarId.equals(new BigInteger(String.valueOf(-1)))) {
            Seminar seminar=seminarService.getSeminarBySeminarId(currentSeminarId);

            Location location = classService.getCallStatusById(classInfo.getId(), currentSeminarId);
            if(location != null) {
                //设定更新
                location.setLongitude(dto.getLongitude());
                location.setLatitude(dto.getLatitude());
                location.setStatus(1);
                location.setClassInfo(classInfo);
                location.setSeminar(seminar);
                classMapper.updateLocationBySeminarIdAndClassId(location);
            }else{
                Location location1 = new Location();
                location1.setLongitude(dto.getLongitude());
                location1.setLatitude(dto.getLatitude());
                location1.setStatus(1);
                location1.setSeminar(seminar);
                location1.setClassInfo(classInfo);
                classService.callInRollById(location1);
            }
        }else{
            currentSeminarId = classService.listCallingSeminarIdByClassId(classId).get(0);
            Seminar seminar=seminarService.getSeminarBySeminarId(currentSeminarId);
            if(!seminar.getFixed()){
                seminarGroupService.automaticallyGrouping(currentSeminarId,classId);
            }

            Location location = new Location();
            location.setClassInfo(classInfo);
            location.setStatus(0);
            classService.updateLocationByclassId(location);

            // 设置自动计算分数
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());

            // 设置5分钟后自动计算
            calendar.add(Calendar.MINUTE,5);
            // 设置调用方法参数
            List<Object> param = new ArrayList<>();
            param.add(currentSeminarId);

            // 插入自动调用计算展示分数的方法
            ((TimerServiceImpl)timerService).insertEvent(calendar.getTime(),
                    "gradeServiceImpl",
                    "countPresentationGrade",
                    param);
        }

        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }


    @GetMapping("/class/{classId}/classgroup")
    public ResponseEntity<GroupVO> getClassGroup(@PathVariable("classId") BigInteger classId) {

        GroupVO vo = new GroupVO();
        StudentVO leader = new StudentVO();
        leader.setId(new BigInteger("2757"));
        leader.setName("张三");
        leader.setNumber("23320152202333");
        vo.setLeader(leader);

        List<StudentVO> members = new ArrayList<>();
        StudentVO student = new StudentVO();
        student.setId(new BigInteger("2756"));
        student.setName("李四");
        student.setNumber("23320152202443");
        members.add(student);

        student = new StudentVO();
        student.setId(new BigInteger("2777"));
        student.setName("王五");
        student.setNumber("23320152202433");
        members.add(student);

        vo.setMembers(members);

        return new ResponseEntity<GroupVO>(vo, HttpStatus.OK);
    }


}

